package com.faiz.algorithm;

import java.util.HashMap;
import java.util.Map;

public class SearchRange {

    public int[] searchRange(int[] nums, int target) {
        if (nums.length < 1) return new int[]{-1, -1};

        int[] res = new int[2];
        int left = searchHelper(nums, target, 0);
        int right = searchHelper(nums, target, 1);
        // 越界处理
        left = left >= nums.length || nums[left] != target ? -1 : left;
        right = right == -1 || right >= nums.length || nums[right] != target ? -1 : right;
        res[0] = left;
        res[1] = right;
        return res;
    }

    /**
     * 搜索左边界或右边界
     * @param nums 数组
     * @param target 查询目标
     * @param leftOrRight 左边界或者有边界（0：左边界， 1：边界）
     * @return 边界
     */
    private int searchHelper(int[] nums, int target, int leftOrRight) {
        int left = 0, right = nums.length;
        while (left < right) {
            int m = left + (right - left) / 2;
            if (target == nums[m]) {
                if (0 == leftOrRight) {
                    right = m;
                } else {
                    left = m + 1;
                }
            } else if (target < nums[m]) {
                right = m;
            } else if (target > nums[m]) {
                left = m + 1;
            }
        }

        if (0 == leftOrRight) {
            return left;
        } else {
            return left - 1;
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("faiz", 550);
        map.computeIfPresent("faiz", (key, value) -> value + 5);
        System.out.println(map);
    }
}
